/*
 * @Descripttion: 工具函数
 */
import {Request} from "@/request/request"
const tool = {}

/* localStorage */
tool.data = {
	set(key, data, datetime = 0) {
		 
        let cacheValue = {
            content: data,
            datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
        }
		return uni.setStorageSync(key, JSON.stringify(cacheValue)); 
	},
	get(key) {
        try {
            const value = JSON.parse(uni.getStorageSync(key))
            if (value) {
                let nowTime = new Date().getTime()
                if (nowTime > value.datetime && value.datetime != 0) {
					uni.removeStorageSync(key);
                    return null;
                } 
                return value.content
            }
            return null
        } catch (err) {
            return null
        }
	},
	remove(key) {
		return uni.removeStorageSync(key);
	},
	clear() {
		return uni.clearStorageSync();
	}
}

tool.playListManage = {
	//播放列表管理
	list(){
		return tool.data.get('playList')
	},
	
	add(data,isNext=0){
		let playList = this.list()
		if(!playList){
			playList = []
		}
		
		if(playList.length===0){
			playList.push(data)
		}else{
		
			let existIndex = null
			playList.forEach((s,index)=>{
				if(s.id===data.id){
					existIndex = index
					return false
				}
			})
			if(existIndex===null){
				let item = data	
				if(isNext===0){
					playList.push(item)
				}else{
					//插入到当前播放歌曲的后面
					let playing =  tool.data.get('playMusic')
					if(playing){
						let playingIndex = null
						playList.forEach((s,index)=>{
							if(s.id===playing.id){
								playingIndex = index
								return false
							}
						})
						if(playingIndex!==null){
							//插入到playingIndex之后
							playList.splice(playingIndex+1, 0,item);
						}
						
					}
				}
				
			}else{
				//如果已经有了
				if(isNext===1){
					let playing =  tool.data.get('playMusic')
						if(playing){
						let playingIndex = null
						playList.forEach((s,index)=>{
							if(s.id===playing.id){
								playingIndex = index
								return false
							}
						})
						if(playingIndex!==null){
							//插入到playingIndex之后
							playList.splice(existIndex, 1);
							playList.splice(playingIndex+1,0,data);
						}
					}
				}
			}
		}
		tool.data.set('playList',playList)
	},
	del(index){
		let playList = this.list()
		playList.splice(index, 1);
		tool.data.set('playList',playList)
	},
	clear(){
		tool.data.remove('playMusic')
		tool.data.remove('playList')
	},
}


tool.collectListManage = {
	//收藏列表管理
	list(){
		return tool.data.get('collectList')
	},
	
	collect(data){
		let collectList = this.list()
		if(!collectList){
			collectList = []
		}
		
		if(collectList.length===0){
			collectList.push(data)
		}else{
		
			let existIndex = null
			collectList.forEach((s,index)=>{
				if(s.id===data.id){
					existIndex = index
					return false
				}
			})
			if(existIndex===null){
				let item = data	
				collectList.push(item)
			}else{
				collectList.splice(existIndex, 1);
			}
		}
		tool.data.set('collectList',collectList)
	},
	del(index){
		let collectList = this.list()
		collectList.splice(index, 1);
		tool.data.set('collectList',collectList)
	},
	clear(){
		tool.data.remove('collectList')
	},
	isCollect(musicID){
		let collectList = this.list()
		let isCollect = 0
		if(!collectList){
			collectList = []
		}
		
		if(collectList.length!==0){
			 
			collectList.forEach((s,index)=>{
				if(s.id===musicID){
					isCollect = 1
					return false
				}
			})
			 
		} 
		return isCollect
		
	},
}

tool.serverManage = {
	//服务器管理
	list(){
		return tool.data.get('server')
	},
	
	add(data){
		let serverList = this.list()
		if(!serverList){
			serverList = []
		}
		//如果没有这个服务器则添加，有的话更新为新的信息
		let existIndex = null
		serverList.forEach((s,index)=>{
			if(s.host===data.host){
				existIndex = index
				return false
			}
		})
		if(existIndex===null){
			let item = {
				host:data.host,
				hostname:data.hostname,
				userList:[
					{
						account:data.account,
						passwd:data.passwd,
					}
				]
				
			}
			serverList.push(item)
		}else{
			//有没有这个用户，有的话更新，没有则插入
			let server = serverList[existIndex]
			let userList = server.userList
			let existUserIndex = null
			userList.forEach((u,index)=>{
				if(u.account===data.account){
					existUserIndex = index
					return false
				}
			})
			 
			if(existUserIndex===null){
				userList.push({
					account:data.account,
					passwd:data.passwd,
				})
				
			}else{
				userList[existUserIndex] = {
					account:data.account,
					passwd:data.passwd,
				}
			}
			server.userList = userList
			serverList[existIndex] = server			 
		}
		tool.data.set('server',serverList)
		
		
	},
	
	del(index){
		let serverList = this.list()
		serverList.splice(index, 1);
		tool.data.set('server',serverList)
	},
}

tool.getRandomNumbers = function(min, max) {
	const range = max - min + 1;
	let randomNum = min + Math.floor(Math.random() * range);
	 
	return randomNum;
}


tool.urlExists = function(url) {
	return new Promise((resolve, reject) => {
		
		uni.request({
			url: url,
			complete:(response)=>{
				resolve(response.statusCode) 
			},
			 
			 
		})
		
	})
	
}



tool.getSid  = function(){
	let sdid = this.data.get('sdid')
	let sid = null
	if(sdid){
		sid =  sdid.sid
	}
	return sid
}

//路由跳转
tool.navTo = function (url) {
	if(!url){
		return 
	} 
	uni.navigateTo({
		url: url
	});
}

//返回上一页
tool.backPageRefresh = function(page) { // page这个值如果你只返回上一页可以不用传，返回上上页就传2，以此类推
	uni.navigateBack({
		delta: page || 1, 
	}); 
}


//加载中
tool.loading = function(){
	uni.showLoading({
		title: '请稍侯'
	});
}
tool.hideloading = function(){
	uni.hideLoading();
}

//轻提示
tool.msg = function(text){
	uni.showToast({
		title: text,
		icon:"none",
		position:"bottom",
		duration: 1000
	});
}

//时间转换
tool.secTotime = function (s) {
    var t = '';
    if(s > -1){
        var hour = Math.floor(s/3600)
        var min = Math.floor(s/60) % 60
        var sec = s % 60
		sec = sec.toFixed(0)
        if(hour < 10) {
		  if(hour!=0){
			 t = '0'+ hour + ":"  
		  }
        } else { 
          t = hour + ":"
        } 
        if(min < 10){
          t += "0"
        } 
        t += min + ":"
        if(sec < 10){
          t += "0"
        } 
        t += sec
    } 
    return t
}

//文件大小转换
tool.formatSize = function(bytes){
	if (bytes === 0){
		return '0 B';
	}
	let k = 1024
	let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
	let i = Math.floor(Math.log(bytes) / Math.log(k));
	return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}



tool.formatLyric=function(lyrics){
	let result = [];
	let arr = lyrics.split("\n");   
	let row = arr.length; //获取歌词行数
	for (let i = 0; i < row; i++) {
		let temp_row = arr[i]; //现在每一行格式大概就是这样"[00:04.302][02:10.00]hello world";
		let temp_arr = temp_row.split("]");//我们可以通过“]”对时间和文本进行分离,变成数组的形式
		 
		let text = temp_arr.pop(); //把歌词文本从数组中剔除出来，获取到歌词文本了！保留最后一个数组
		
		temp_arr.forEach(element => {
		     
			  let obj = {};
			  let time_arr = element.substr(1, element.length - 1).split(":");//先把多余的“[”去掉，再分离出分、秒
			  let s = parseInt(time_arr[0]) * 60 + Math.ceil(time_arr[1]); //把时间转换成与currentTime相同的类型，方便待会实现滚动效果
			  // console.log(s);
			  obj.time = s;//时间
			  obj.text = text;//歌词
			  if(text!=='' && text!=='\r'){
				 result.push(obj);    
			  }
			  
		});
		
		
	} 
	result.sort(this.sortRule)  
	return result
}

tool.sortRule=function(a,b){
	return a.time - b.time;
}


export default tool
